package com.wangcanxuan.www.util.pool.factory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义的线程工厂，感觉好像没什么用，只是原子操作类命个名。。
 *
 * @author HHLJ
 * @date 2022/03/23
 */
public class CheckConnectionThreadFactory implements ThreadFactory {
    /**
     * 线程池编号
     */
    private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
    /**
     * 一个线程组
     */
    private final ThreadGroup group;

    /**
     * 线程编号
     */
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    /**
     * 名称前缀
     */
    private final String namePrefix;

    public CheckConnectionThreadFactory(String nameFormat) {
        // 获得安全管理器
        SecurityManager securityManager = System.getSecurityManager();
        group = (securityManager != null) ? securityManager.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        namePrefix = nameFormat + "-" + POOL_NUMBER.getAndIncrement() + "-MyThread-";
    }


    /**
     * 创建新线程
     *
     * @param r r
     * @return {@link Thread}
     */
    @Override
    public Thread newThread(Runnable r) {
        //实例化线程对象
        return new Thread(group,r,
                namePrefix + threadNumber.getAndIncrement());
    }
}
